package util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import java.util.Arrays;

/**
 * 将汉语拼音得字符映射为字母字符串
 */
public class PinyinUtil {
    //定义汉语拼音的配置，全局常量
    private static final HanyuPinyinOutputFormat FORMAT;

    private static final String CHINESE_PATTERN = "[\\u4E00-\\u9FA5]";

    static{
        FORMAT = new HanyuPinyinOutputFormat();
        //将转换后的拼音全小写
        FORMAT.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        //设置转换后的英文字母是否带音调
        FORMAT.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        //特殊拼音用v代替  绿
        FORMAT.setVCharType(HanyuPinyinVCharType.WITH_V);
    }

    /**
     * 传入文件名，将其转为字母字符串全拼和首字母小写字符串
     * @param fileName
     * @return
     */
    public static String[] getPinyinByFileName(String fileName) {
        String[] ret = new String[2];
        StringBuilder allNameAppender = new StringBuilder();
        StringBuilder firstCaseAppender = new StringBuilder();
        for(char c : fileName.toCharArray()) {
            try {
                String[] pinyins = PinyinHelper.toHanyuPinyinStringArray(c,FORMAT);
                if(pinyins == null || pinyins.length == 0) {
                    //非中文直接保留
                    allNameAppender.append(c);
                    firstCaseAppender.append(c);
                }else {
                    //中文字符，取第一个多音字的返回值
                    allNameAppender.append(pinyins[0]);
                    firstCaseAppender.append(pinyins[0].charAt(0));
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                //碰到非中文直接保留
                allNameAppender.append(c);
                firstCaseAppender.append(c);
            }
        }
        ret[0] = allNameAppender.toString();
        ret[1] = firstCaseAppender.toString();
        return ret;
    }
    public static void main(String[] args) throws BadHanyuPinyinOutputFormatCombination {
        String str = "中华人民共和国";
        System.out.println(Arrays.toString(getPinyinByFileName(str)));
        System.out.println("-------------------------------");
        String str1 = "中123国456好abc";
        System.out.println(Arrays.toString(getPinyinByFileName(str1)));
    }

    public static boolean containsChinese(String fileName) {
        return fileName.matches(".*" +CHINESE_PATTERN +".*");
    }
}


